package main

import (
    "fmt"
    "net"
    "sync"
    "time"
)

func handleConnection(conn net.Conn, wg *sync.WaitGroup) {
    defer wg.Done()
    defer conn.Close()
    buffer := make([]byte, 1024)
    for {
        // 设置一个超时时间，比如5秒
        conn.SetReadDeadline(time.Now().Add(5 * time.Second))
        n, err := conn.Read(buffer)
        if err!= nil {
            fmt.Println("读取客户端数据出错:", err)
            return
        }
        message := string(buffer[:n])
        fmt.Println("收到客户端消息:", message)
        _, err = conn.Write([]byte("服务端已收到: " + message))
        if err!= nil {
            fmt.Println("向客户端发送响应出错:", err)
            return
        }
    }
}

func main() {
    listener, err := net.Listen("tcp", "127.0.0.1:8080")
    if err!= nil {
        fmt.Println("监听端口出错:", err)
        return
    }
    defer listener.Close()

    fmt.Println("服务端启动，等待客户端连接...")
    var wg sync.WaitGroup
    for {
        conn, err := listener.Accept()
        if err!= nil {
            fmt.Println("接受客户端连接出错:", err)
            continue
        }
        wg.Add(1)
        go handleConnection(conn, wg)
    }
    wg.Wait()
}